package feces.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import feces.model.ClientOrder;
import feces.model.ClientOrderList;
import feces.model.Supplier;
import feces.servlet.RESTfulServlet.Response;
import feces.servlet.SupplierServlet.Dictionary;
import feces.utility.Utility;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.sql.Date;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;


public class BusinessCountServlet extends RESTfulServlet {

	/**
	 * 商品订购排行榜
	 * 
	 */
		
	
	
	/**
	 * 响应GET请求
	 * @return 查询结果
	 */
	@Override
	protected Response<List<ClientOrderList>> responseRead(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		Date d1=Utility.toDate(request.getParameter("date_1"));
		Date d2=Utility.toDate(request.getParameter("date_2"));
		System.out.println(d1);
		System.out.println(d2);
		List<ClientOrder>  list_order_1=findAll(ClientOrder.class);
		List<ClientOrderList> list_order_2=new ArrayList<ClientOrderList>();
		for (ClientOrder co : list_order_1) {
			List<ClientOrderList> c=co.getProducts();
			Date d3=co.getOrderdate();
			if(d3!=null){
			if(d3.after(d1)&&d3.before(d2)){
			list_order_2.addAll(c);
			}
		}
		}
		Collections.sort(list_order_2,new Comparator<ClientOrderList>(){   
	           public int compare(ClientOrderList arg0, ClientOrderList arg1) {   
	               return arg0.getProduct_id().compareTo(arg1.getProduct_id());   
	            }   
	        });
	 for (int i = 1; i<list_order_2.size(); i++) {  
		 
		   if (list_order_2.get(i).getProduct_id()==list_order_2.get(i-1).getProduct_id()) {
			   list_order_2.get(i-1).setProduct_number(list_order_2.get(i).getProduct_number()
				   +list_order_2.get(i-1).getProduct_number());
			   list_order_2.remove(i);	
			   i--;
		   }
		   
	 }
	return succeed(list_order_2);
	}	
}
